import fetch from "cross-fetch";

export const SET_HOT = "SET_HOT";
export const SET_FETCHING = "SET_FETCHING";

export function setHot(cities) {
    return {
        type: SET_HOT,
        cities,
    };
}

/* 获取同步action */
export function setFeching(value) {
    return {
        type: SET_FETCHING,
        value
    };
}

/* 获取异步action（一个返回promise的函数） */
export function fetchHotAsync() {
    return (dispatch, getState) => {

        // 将isFeching首先设置为true
        dispatch(setFeching(true));

        return fetch(
            "https://m.maizuo.com/gateway?k=4448570", 
            {
                headers: {
                    "X-Host": "mall.film-ticket.city.list",
                },
            }
        )
            .then((res) => res.json())
            .then((data) => {
                console.log("data=", data);

                const hotCities = data.data.cities
                    .filter((city) => city.isHot)
                    .map((city) => city.name);
                    
                dispatch(setHot(hotCities));
            })
            .catch((err) => console.log("err=", err))
            .finally(() => dispatch(setFeching(false)))
    };
}
